import { LockTwoTone, UserOutlined } from '@ant-design/icons';
import { Alert, message } from 'antd';
import React, { useState } from 'react';
import ProForm, { DrawerForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { useIntl, connect, FormattedMessage } from 'umi';
import type { Dispatch } from 'umi';
import type { StateType } from '@/models/login';
import type { LoginParamsType } from '@/services/login';
import type { ConnectState } from '@/models/connect';
import { extend } from 'umi-request';
import logo from '../../../assets/logo.png';
import styles from './index.less';
export type LoginProps = {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
};
const request = extend({
  credentials: 'include',
  // 默认请求是否带上cookie
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

const LoginMessage: React.FC<{
  content: string;
}> = ({
  content
}) => <Alert style={{
  marginBottom: 24
}} message={content} type='error' showIcon />;

const Login: React.FC<LoginProps> = props => {
  const {
    userLogin = {},
    submitting
  } = props;
  const {
    errorCode,
    type: loginType
  } = userLogin;
  const [type, setType] = useState<string>('account');
  const intl = useIntl();
  const [forget, setForget] = useState<boolean>(false);

  const handleSubmit = (values: LoginParamsType) => {
    const {
      dispatch
    } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values,
        type
      }
    });
  };

  var autoLogin = false;
  var autoFlag: string = (localStorage.getItem('autoLogin') as string);
  var username = '';

  if (autoFlag === null) {
    autoLogin = true;
  } else {
    autoLogin = autoFlag === 'true' ? true : false;

    if (autoLogin) {
      username = (localStorage.getItem('username') as string);
    }
  }
//_测试版
  return <div className={styles.main} >
      <div className={styles.system} ><span >销售管理系统</span></div>
      <div className={styles.title} ><span >用户登录</span><div className={styles.line} ></div></div>

      <ProForm initialValues={{
      autoLogin: autoLogin,
      username: username
    }} submitter={{
      searchConfig: {
        submitText: '登录'
      },
      render: (_, dom) => dom.pop(),
      submitButtonProps: {
        loading: submitting,
        size: 'large',
        style: {
          width: '100%',
          backgroundColor: '#E92B3A',
          border: '#E92B3A 1px solid'
        }
      }
    }} onFinish={values => {
      if (values.autoLogin) {
        localStorage.setItem('autoLogin', 'true');
        localStorage.setItem('username', values.username);
      } else {
        localStorage.removeItem('autoLogin');
        localStorage.removeItem('username');
      }

      handleSubmit((values as LoginParamsType));
      return Promise.resolve();
    }}>
        {errorCode && errorCode != '200' && !submitting && <LoginMessage content={intl.formatMessage({
        id: 'pages.login.accountLogin.errorMessage',
        defaultMessage: '账户或密码错误'
      })} />}
        {type === 'account' && <>
            <h3  >用户名</h3>
            <ProFormText name='username' fieldProps={{
          size: 'large',
          prefix: <UserOutlined className={styles.prefixIcon}/>
        }} placeholder={intl.formatMessage({
          id: 'pages.login.username.placeholder',
          defaultMessage: '用户名'
        })} rules={[{
          required: true,
          message: <FormattedMessage id='pages.login.username.required' defaultMessage='请输入用户名!'/>
        }]}/>
             <h3>登录密码</h3>
            <ProFormText.Password name='password' fieldProps={{
          size: 'large',
          prefix: <LockTwoTone className={styles.prefixIcon} />
        }} placeholder={intl.formatMessage({
          id: 'pages.login.password.placeholder',
          defaultMessage: '密码'
        })} rules={[{
          required: true,
          message: <FormattedMessage id='pages.login.password.required' defaultMessage='请输入密码！'/>
        }]}/>
          </>}

        <div style={{
        marginBottom: 20
      }} >
          <ProFormCheckbox noStyle name='autoLogin' >
            记住账号
          </ProFormCheckbox>

          <a style={{
          float: 'right'
        }} onClick={() => {
          setForget(true);
        }}>忘记密码
          </a>
        </div>
      </ProForm>
      <DrawerForm title='通过邮箱重置密码' onVisibleChange={setForget} visible={forget} onFinish={async (values: any) => {
      var val = await request('/xwyl/user/sendResetMail', {
        method: 'POST',
        requestType: 'form',
        data: { ...values,
          method: 'post'
        }
      });

      if (val.errorCode === '200') {
        message.success(val.errorMessage);
        return true;
      } else {
        message.error(val.errorMessage);
        return false;
      }
    }}>
           <ProFormText name='param' label='邮箱' placeholder='请输入邮箱' width='md' rules={[{
        required: true
      }, {
        pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
        message: '邮箱格式不正确'
      }, {
        max: 50,
        message: '邮箱不得超过50字符'
      }]}/>

         </DrawerForm>
    </div>;
};

export default connect(({
  login,
  loading
}: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login']
}))(Login);